﻿using System;
using System.Collections.Generic;
using ExFlash.Records;

namespace ExFlash.Actions
{
    public class ActionTry : ActionRecord
    {
        private readonly int _swfVersion;

        public Boolean CatchInRegisterFlag
        {
            get;
            protected set;
        }

        public Boolean FinallyBlockFlag
        {
            get;
            protected set;
        }

        public Boolean CatchBlockFlag
        {
            get;
            protected set;
        }

        public ushort TrySize
        {
            get;
            protected set;
        }

        public ushort CatchSize
        {
            get;
            protected set;
        }

        public ushort FinallySize
        {
            get;
            protected set;
        }

        public StringRecord CatchName
        {
            get;
            protected set;
        }

        public Byte CatchRegister
        {
            get;
            protected set;
        }

        public List<ActionRecord> TryBody
        {
            get;
            protected set;
        }

        public List<ActionRecord> CatchBody
        {
            get;
            protected set;
        }

        public List<ActionRecord> FinallyBody
        {
            get;
            protected set;
        }

        public ActionTry(ushort len, int version)
            : base((byte)ActionCodes.ActionTry, len)
        {
            _swfVersion = version;
        }

        public override void SwfDeserialize(BinaryBitReader reader)
        {
            reader.SkipBits(5);
            CatchInRegisterFlag = reader.ReadBoolean();
            FinallyBlockFlag = reader.ReadBoolean();
            CatchBlockFlag = reader.ReadBoolean();

            reader.AlignBits();

            TrySize = reader.ReadUInt16();
            CatchSize = reader.ReadUInt16();
            FinallySize = reader.ReadUInt16();

            if (!CatchInRegisterFlag)
            {
                CatchName = new StringRecord(_swfVersion);
                CatchName.SwfDeserialize(reader);
            }
            else
            {
                CatchRegister = reader.ReadByte();
            }

            TryBody = ActionAssistant.GetActionsByLength(reader, TrySize, _swfVersion);

            if (CatchBlockFlag)
            {
                CatchBody = ActionAssistant.GetActionsByLength(reader, CatchSize, _swfVersion);
            }

            if (FinallyBlockFlag)
            {
                FinallyBody = ActionAssistant.GetActionsByLength(reader, FinallySize, _swfVersion);
            }
        }

        public override void SwfSerialize(byte[] arr, ref int offset)
        {
            throw new NotImplementedException();
        }
    }
}
